package com.yi.wood.web.ctrl;

import com.yi.wood.utils.ImageUtil;
import com.yi.wood.web.session.SessionVerCode;
import com.yi.wood.web.util.CommonStrUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author MoYi
 * Created time 2019/5/29 15:44
 * 一些通用接口
 */
@RestController
@RequestMapping("/common")
public class CommonCtrl extends BaseCtrl{

    @Resource
    private SessionVerCode sessionVerCode;

    /**
     * 生成验证码
     */
    @RequestMapping(value = "/verCode",method = RequestMethod.GET)
    public Object getVerCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String sessionId = request.getSession().getId();
        String verCode = CommonStrUtil.getRandomStr(4);
        sessionVerCode.cacheVerCode(sessionId, verCode);
        BufferedImage image = ImageUtil.createVerCodeImage(verCode);
        String base64Str = ImageUtil.imageToBase64(image);
        return put("image","data:image/png;base64,"+base64Str);
    }

    /**
     * 生成滑动图片验证码
     */
    @RequestMapping(value = "/slideVerCode",method = RequestMethod.GET)
    public Object getImgSlide() throws Exception {
        File file = new File("F:\\Temp\\img\\1.png");
        BufferedImage[] images =ImageUtil.createVerCodeByFileImage(file,200,50,60,50);
        String base64Str = ImageUtil.imageToBase64(images[0]);
        String oriBase64Str = ImageUtil.imageToBase64(images[1]);
        String prefix = "data:image/png;base64,";
        put("oriImage", prefix+oriBase64Str);
        put("top",50);
        return put("image",prefix+base64Str);
    }
}
